package com.lingyuan.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.lingyuan.common.core.domain.vo.pms.SearchResult;
import com.lingyuan.common.core.domain.vo.pms.SkuAttrVo;
import com.lingyuan.service.SearchsService;
import lombok.extern.log4j.Log4j2;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @ClassName SearchsServiceImpl
 * @Description 描述
 * @Author guoxin
 * @Date 2024/9/21 12:20
 */
@Log4j2
@Service
public class SearchsServiceImpl implements SearchsService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    public static final String INDEX_NAME="lingyuan_product";
    /**
     * 功能:批量添加
     */
    @Override
    public void bulkAdd(List<SkuAttrVo> skuAttrVos) {
        try {
        log.info("批量添加商品信息");
        BulkRequest bulkRequest = new BulkRequest(INDEX_NAME);
        skuAttrVos.stream().forEach(skuAttrVo ->
                bulkRequest.add(new IndexRequest(INDEX_NAME).id(skuAttrVo.getSpuId().toString()).source(JSONObject.toJSONString(skuAttrVo), XContentType.JSON))
        );
            restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.info("批量添加商品信息失败");
        }
    }
    /**
     * TODO es简单查询 待完善
     * 功能:商品多条件搜索
     */
    @Override
    public SearchResult search() {
        SearchRequest searchRequest = new SearchRequest(INDEX_NAME);
        SearchResult searchResult = new SearchResult();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //查询商品列表
        searchSourceBuilder.query(boolQueryBuilder);
        searchRequest.source(searchSourceBuilder);
        try {
        SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        searchResult.setTotal(search.getHits().getTotalHits().value);
            List<SkuAttrVo> skuVoList = new ArrayList<>();
            for (org.elasticsearch.search.SearchHit hit : search.getHits()) {
                Map<String, Object> sourceAsMap = hit.getSourceAsMap();
                SkuAttrVo skuAttrVo = new SkuAttrVo();
                skuAttrVo.setSkuId(((Number) sourceAsMap.get("skuId")).longValue());
                skuAttrVo.setSpuId(((Number) sourceAsMap.get("spuId")).longValue());
                skuAttrVo.setSkuTitle((String) sourceAsMap.get("skuTitle"));
                BigDecimal price = new BigDecimal(Double.toString(((Number) sourceAsMap.get("price")).doubleValue()));
                skuAttrVo.setPrice(price);
                skuAttrVo.setCatalogId(((Number) sourceAsMap.get("catalogId")).longValue());
                skuAttrVo.setBrandId(((Number) sourceAsMap.get("brandId")).longValue());
                skuAttrVo.setBrandName((String) sourceAsMap.get("brandName"));
                skuAttrVo.setCatalogName((String) sourceAsMap.get("catalogName"));

                List<SkuAttrVo.attrVo> attrVoList = new ArrayList<>();
                List<Map<String, Object>> attrVoListMap = (List<Map<String, Object>>) sourceAsMap.get("attrVoList");
                for (Map<String, Object> attrVoMap : attrVoListMap) {
                    SkuAttrVo.attrVo attrVo = new SkuAttrVo.attrVo();
                    attrVo.setAttrId(((Number) attrVoMap.get("attrId")).longValue());
                    attrVo.setAttrName((String) attrVoMap.get("attrName"));
                    attrVo.setAttrValue((String) attrVoMap.get("attrValue"));
                    attrVoList.add(attrVo);
                }
                skuAttrVo.setAttrVoList(attrVoList);
                skuVoList.add(skuAttrVo);
            }
            searchResult.setSkuVoList(skuVoList);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
      return  searchResult;
    }
    /**
     * 功能: 删除商品
     */
    @Override
    public void del(Long spuId) {
        DeleteRequest deleteRequest = new DeleteRequest(INDEX_NAME,spuId.toString());
        try {
            restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
